//
//  SlideView.m
//  LvXi_newVersion
//
//  Created by 王敏 on 16/8/12.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "SlideView.h"

#import "LeftImageCell.h"

#import "HomeSlideHeader.h"

#import "SlideTopImageCell.h"

#import "LXMineViewController.h"

#import "CommentController.h"

#import "LXShopCartController.h"

#import "LXStoreViewController.h"

#import "LXFootprintViewController.h"

@interface BottomTool : UIView

@end


@implementation BottomTool
-(id)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        self.backgroundColor = [UIColor clearColor];
        NSArray * images = @[@"center_uncheck",@"collection",@"footprint"];
        NSArray * names = @[@"个人中心",@"收藏",@"足迹"];
        CGFloat W = self.width/3.0;
        CGFloat H = self.height;
        for (int i = 0; i<3; i++) {
            UIView * containerView = [[UIView alloc] initWithFrame:CGRectMake(i*W, 0, W, H)];
            [containerView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleClick:)]];
            containerView.tag = i;
            UIImageView * imgv = [[UIImageView alloc] initWithFrame:CGRectZero];
            imgv.image = [UIImage imageNamed:images[i]];
            imgv.size = imgv.image.size;
            imgv.x = Ratio_home_slide_bottomTool_image_marginLeft * self.width;
            imgv.y = 0;
            [containerView addSubview:imgv];
            UILabel * textLabel = [[UILabel alloc] initWithFrame:CGRectZero];
            textLabel.text = names[i];
            textLabel.font = [UIFont systemFontOfSize:ISBigScreen?14:12];
            textLabel.width = containerView.width - imgv.right;
            textLabel.height = self.height;
            textLabel.x  = imgv.right + Ratio_home_slide_bottomTool_text_marginLeft * self.width;
            textLabel.y = 0;
            [containerView addSubview:textLabel];
            [self addSubview:containerView];
        }
    }
    return self;
}

-(void)handleClick:(UITapGestureRecognizer*)gesture{
    switch (gesture.view.tag) {
        case 0:{//个人中心
            if(LoginState){
            LXMineViewController * vc = [[LXMineViewController alloc] init];
                [[self getCurrentVC].navigationController pushViewController:vc animated:YES];
            }else{
                [[self getCurrentVC] presentViewController:[[LXLoginViewController alloc] init] animated:YES completion:nil];
            }
        }break;
        case 1:{
            if(LoginState){
                [[self getCurrentVC].navigationController pushViewController:[[LXStoreViewController alloc] init] animated:YES];
            }else{
                [[self getCurrentVC] presentViewController:[[LXLoginViewController alloc] init] animated:YES completion:nil];
            }
        }break;
        case 2:{

            if(LoginState){

                [[self getCurrentVC].navigationController pushViewController:[[LXFootprintViewController alloc] init] animated:YES];
            }else{
                [[self getCurrentVC] presentViewController:[[LXLoginViewController alloc] init] animated:YES completion:nil];
            }
        }break;
        default:
            break;
    }
}
@end



//MARK:侧滑视图
@interface SlideView()<UITableViewDataSource,UITableViewDelegate,HomeSlideHeaderDelegate>
/**
 *  存储cell高度的可变字典
 */
@property(nonatomic,strong)NSMutableDictionary * cellHeights;
-(void)addCellHeight:(CGFloat)cellHeight indexPath:(NSIndexPath*)indexPath;
/**
 *  从cell高度 cellHeights 可变字典中 以cell 的 indexPath为关键字取Cell 的高度
 *
 *  @param indexPath NSIndexPath cell 的 indexPath
 *
 *  @return CGFloat cell 的高度
 */
-(CGFloat)cellHeightForIndexPath:(NSIndexPath*)indexPath;


@property(nonatomic,strong)HomeSlideHeader * headerView;
@end

@implementation SlideView
static NSString * leftImageCellID = @"leftImageCellID";
static NSString * topImageCellID = @"topImageCellID";
+(instancetype)slideView{
    SlideView * slideView = [[[self class] alloc] _init];
    return slideView;
}

-(id)_init{
    if(self = [super initWithFrame:CGRectMake(-ScreenWidth, 0, ScreenWidth, ScreenHeight)]){
        self.backgroundColor = [UIColor clearColor];
        [self addSubview:self.containerView];
        [self.containerView addSubview:self.tableView];
        UIButton * backButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [self addSubview:backButton];
        backButton.x = self.tableView.width;
        backButton.y = 0;
        backButton.width = ScreenWidth - self.tableView.width;
        backButton.height = ScreenHeight;
        backButton.backgroundColor = [UIColor clearColor];
        [backButton addTarget:self action:@selector(hidden) forControlEvents:UIControlEventTouchUpInside];
        [self addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureEvents:)]];
        BottomTool * tool = [[BottomTool alloc] initWithFrame:CGRectMake(0, 0, self.containerView.width, 23)];
        tool.y = ScreenHeight - tool.height - 15.f/667.f * ScreenHeight;
        [self.containerView addSubview:tool];
        [self.containerView bringSubviewToFront:tool];
    }
    return self;
}


//MARK:懒加载tableView
-(UITableView*)tableView{
    if(_tableView == nil){
        UITableView * tableView = [[UITableView alloc]initWithFrame:self.containerView.bounds style:UITableViewStyleGrouped];
        tableView.backgroundColor = [UIColor clearColor];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.delegate = self;
        tableView.dataSource = self;
        HomeSlideHeader * headerView = [[HomeSlideHeader alloc] initWithFrame:CGRectMake(0, 0, tableView.width, ScreenHeight*Ratio_home_slide_header_height)];
        headerView.delegate = self;
        tableView.tableHeaderView = headerView;
        self.headerView = headerView;
        
        
        tableView.sectionFooterHeight = globalMargin;
        tableView.sectionHeaderHeight = 0;
        
        [tableView registerClass:[LeftImageCell class] forCellReuseIdentifier:leftImageCellID];
        
        [tableView registerClass:[SlideTopImageCell class] forCellReuseIdentifier:topImageCellID];
        _tableView = tableView;
    }
    return _tableView;
}

//MARK:懒加载容器View
-(UIView*)containerView{
    if(_containerView == nil){
        _containerView = [[UIView alloc] initWithFrame:CGRectMake(-ScreenWidth*Ratio_leftVC, 0, ScreenWidth*Ratio_leftVC, ScreenHeight)];
        _containerView.userInteractionEnabled = YES;
        NSArray * colors = [NSArray arrayWithObjects:
                            (id)[HexColor(@"#DDEFDB") CGColor],
                            (id)[HexColor(@"#8DBB7A") CGColor], nil];
        [_containerView addGradientLayerWithColors:colors starPoint:CGPointMake(0.6, 0) endPoint:CGPointMake(0.5, 1.0)];
    }
    return _containerView;
}

#pragma mark - tableView 分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

#pragma mark - tableView 各组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger categorys = [ShareCategory shareCategory].categorys.count;
    NSInteger c = categorys/4 + (((categorys%4)!=0)?1:0);
    return section==0?5:c;
}
#pragma mark - 具体cell
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell;
    if(indexPath.section == 0){
        NSArray * names = @[@"首页",@"分佣",@"添加优惠码",@"设置",@"分类"];
        NSArray * images = @[@"Home_page_uncheck",@"commission_uncheck",@"coupons_uncheck",@"setting_uncheck",@"classification_selected"];
        LeftImageCell * leftImageCell = [tableView dequeueReusableCellWithIdentifier:leftImageCellID];
        [leftImageCell setImage:images[indexPath.row] name:names[indexPath.row]];
        leftImageCell.callBack = ^(LeftImageCell * cell){
          if([cell.name isEqualToString:@"首页"])
            [self hidden];
            
        };
        [self addCellHeight:leftImageCell.cellHeight indexPath:indexPath];
        cell = leftImageCell;
    }else{
        SlideTopImageCell * topImageCell = [tableView dequeueReusableCellWithIdentifier:topImageCellID];
        NSArray * categorys = [ShareCategory shareCategory].categorys;
        NSMutableArray * names = [NSMutableArray array];
        NSMutableArray * images = [NSMutableArray array];
        NSMutableArray * cates = [NSMutableArray array];
        if(categorys.count/((indexPath.row+1)*4)>=1){
            for (int i = 0; i<4; i++) {
                NSString * img = [categorys[(indexPath.row)*4+i] small_pic];
                [names addObject:[categorys[(indexPath.row)*4+i] cat_name]];
                [images addObject:img&&img.length!=0?img:@""];
                [cates addObject:categorys[(indexPath.row)*4+i]];
            }
        }
        else{
            for (int i = 0; i<categorys.count%4;i++) {
                NSString * img = [categorys[(indexPath.row)*4+i] small_pic];
                [names addObject:[categorys[(indexPath.row)*4+i] cat_name]];
                [images addObject:img&&img.length!=0?img:@""];
                [cates addObject:categorys[(indexPath.row)*4+i]];
            }
        }
        topImageCell.cates = cates;
        [topImageCell setImages:images names:names];
        cell = topImageCell;
        [self addCellHeight:topImageCell.cellHeight indexPath:indexPath];
    }
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self cellHeightForIndexPath:indexPath];
}

/**cell高度相关*/
-(NSMutableDictionary*)cellHeights{
    if(_cellHeights == nil){
        _cellHeights = [NSMutableDictionary dictionary];
    }
    return _cellHeights;
}

-(void)addCellHeight:(CGFloat)cellHeight indexPath:(NSIndexPath*)indexPath{
    [self.cellHeights setObject:@(cellHeight) forKey:[indexPath string]];
}

-(CGFloat)cellHeightForIndexPath:(NSIndexPath*)indexPath{
    return [self.cellHeights[[indexPath string]] floatValue];
}


/**动画相关*/
-(void)show{
    [self.tableView reloadData];
    [self.headerView upDate];
    self.x = 0;
    if(self.beginShowBlock){
        self.beginShowBlock();
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LxRoundScrollViewStopTimer" object:nil];
    [self.superview bringSubviewToFront:self];
    [UIView animateWithDuration:0.2 animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
        self.containerView.x =0;
        if(self.showCompleteBlock){
            self.showCompleteBlock();
        }
    }];
}

-(void)hidden{

    if(self.beginHiddenBlock){
        self.beginHiddenBlock();
    }
    [UIView animateWithDuration:0.2 animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.0];
        self.containerView.x = -self.containerView.width ;

    }completion:^(BOOL finished) {
        [self.superview sendSubviewToBack:self];
        self.x = -ScreenWidth;
        if(self.hiddenCompleteBlock){
            self.hiddenCompleteBlock();
        };
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LxRoundScrollViewStartTimer" object:nil];
    }];
}


-(void)panGestureEvents:(UIPanGestureRecognizer*)gesture{
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:{
        }break;
        case UIGestureRecognizerStateChanged:{
            CGFloat offsetX = [gesture translationInView:self].x;
            if(offsetX<=0){
                self.containerView.x = offsetX;
                self.backgroundColor = [UIColor colorWithWhite:0 alpha:(1+offsetX/self.width)-0.4];
            }
            
            if(self.dragBlock)self.dragBlock(offsetX);
        }break;
            
        case UIGestureRecognizerStateEnded:{
            if(self.containerView.x< - self.containerView.width * 0.3){
                [self hidden];
            }
            else{
                [self show];
            }
        }break;
        default:
            break;
    }
}


-(void)upDate{
    [self.headerView upDate];
}

@end
